package com.app.bimo.commonbusiness.network;

import android.util.Log;

import com.app.bimo.commonbusiness.bean.BaseResult;
import com.app.bimo.commonbusiness.network.Exception.ApiException;
import com.app.bimo.commonbusiness.network.Exception.CustomException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.functions.Function;

/**
 * 对返回的数据进行处理，区分异常的情况。
 */

public class ResponseTransformer {

    public static <T> ObservableTransformer<BaseResult<T>, T> handleResult() {
        return upstream -> upstream
                .onErrorResumeNext(new ErrorResumeFunction<>())
                .flatMap(new ResponseFunction<>());
    }

    public static <T> ObservableTransformer<BaseResult<T>, T> handleResultHaveCache() {
        return upstream -> upstream
                .onErrorResumeNext(new ErrorResumeFunctionHaveCahce<>())
                .flatMap(new ResponseFunction<>());
    }

    public static <T> Observable<T> handleResultEmpty(){
        return new Observable<T>() {
            @Override
            protected void subscribeActual(Observer<? super T> observer) {
                observer.onError(new ApiException(CustomException.EMPTY_ERROR,""));
            }
        };
    }


    /**
     * 非服务器产生的异常，比如本地无无网络请求，Json数据解析错误等等。
     *
     * @param <T>
     */
    private static class ErrorResumeFunction<T> implements Function<Throwable, ObservableSource<? extends BaseResult<T>>> {

        @Override
        public ObservableSource<? extends BaseResult<T>> apply(Throwable throwable) throws Exception {
            return Observable.error(CustomException.handleException(throwable));
        }
    }

    /**
     * 非服务器产生的异常，比如本地无无网络请求，Json数据解析错误等等。有缓存，返回空发射源
     *
     * @param <T>
     */
    private static class ErrorResumeFunctionHaveCahce<T> implements Function<Throwable, ObservableSource<? extends BaseResult<T>>> {

        @Override
        public ObservableSource<? extends BaseResult<T>> apply(Throwable throwable) throws Exception {
            return Observable.empty();
        }
    }

    /**
     * 服务其返回的数据解析
     * 正常服务器返回数据和服务器可能返回的exception
     *
     * @param <T>
     */
    private static class ResponseFunction<T> implements Function<BaseResult<T>, ObservableSource<T>> {

        @Override
        public ObservableSource<T> apply(BaseResult<T> tResponse) throws Exception {
            int code = tResponse.getCode();
            String message = tResponse.getMsg();
            Log.e("ok_message", message);
            if (code == 200) {
                return Observable.just(tResponse.getResult());
            } else {
                return Observable.error(new ApiException(code, message));
            }
        }
    }


}
